package com.nondo.rdp.finance.endpoint.api.app;

import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.core.common.CommUtil;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.Feedback;
import com.nondo.rdp.finance.service.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController("apiAppFeedback")
@RequestMapping("/api/app/feedback")
public class FeedbackEndpoint {
    @Autowired
    FeedbackService feedbackService;

    @RequestMapping("")
    public View info(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody Feedback feedbackPost, BindingResult result) {
        View view = new View(20000, "感谢你的反馈，我们会倾听你的意见");

        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        }

        User user = UserUtils.getUser(request, response);

        //每个用户每天最多提交3次意见反馈
        List<Feedback> feedbackList = this.feedbackService.findAllByUserAndCreateDateGreaterThanEqual(user, CommUtil.getTodayZeroTime());
        if (feedbackList.size() >= 3) {
            return View.ofOk("感谢你的反馈，我们会倾听你的意见");
        }

        Feedback feedback = new Feedback();
        feedback.setBody(feedbackPost.getBody());
        feedback.setUser(user);

        this.feedbackService.save(feedback);

        return view;
    }
}